package com.zhiqianbao.activity;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.zhiqianbao.R;
import com.zhiqianbao.adapter.PhoneContactListAdapter;
import com.zhiqianbao.entity.PhoneContact;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by 亮 on 2015/12/26.
 */
public class ContactsMobileActivity extends BaseActivity {

    private String TAG = ContactsMobileActivity.class.getSimpleName();

    private PhoneContactListAdapter adapter;
    private Map<Integer, PhoneContact> contactIdMap = null;
    public ListView listView;
    public EditText searchContact;
    public ImageView btnCleanSearch;
    public RelativeLayout layoutButton;
    public Button buttonGoSetting;
    private List<PhoneContact> list;

    //是否上传过
    boolean isUploaded = false;

    /**
     * 查询条件
     */
    private String query;
    /**
     * 异步查询数据库对象
     */
    private AsyncQueryHandler asyncQueryHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts_mobile);

        String editInfo = (String) getIntent().getSerializableExtra("edit");
        //修改新增编辑页面过来的
        if (editInfo.equals("1")) {
            Log.i(TAG, "编辑页面跳转选择");
            isUploaded = false;
        } else {
            Log.i(TAG, "完善信息页面跳转选择");
            isUploaded = false;
        }

        init();
        //绑定view
        listView=(ListView)findViewById(R.id.listView);
        searchContact=(EditText)findViewById(R.id.search_contact);
        btnCleanSearch=(ImageView)findViewById(R.id.btn_clean_search);
        layoutButton=(RelativeLayout)findViewById(R.id.layout_button);
        buttonGoSetting=(Button)findViewById(R.id.button_go_setting);

        asyncQueryHandler = new ContactsAsyncQueryHandler(getContentResolver());
        startQuery("");



        searchContact.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(!StringUtils.isBlank(s.toString())) {
                    btnCleanSearch.setVisibility(View.VISIBLE);
                } else {
                    btnCleanSearch.setVisibility(View.GONE);
                }

                startQuery(s.toString());
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        //绑定列表点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PhoneContact phoneContact = list.get(position);
                //数据是使用Intent返回
                Intent intent = new Intent();
                intent.putExtra("phone", phoneContact);
                //设置返回数据
                ContactsMobileActivity.this.setResult(RESULT_OK, intent);
                //关闭Activity
                ContactsMobileActivity.this.finish();
            }
        });

        //绑定清除搜索内容事件
        btnCleanSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchContact.setText("");
            }
        });
        buttonGoSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Context context = ContactsMobileActivity.this.getApplicationContext();

                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_SETTINGS);
                ContactsMobileActivity.this.startActivity(intent);

            }
        });

    }

    private void startQuery(String name) {
        query = name;
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;//联系人Uri
        // 查询的字段
        String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.DATA1,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                ContactsContract.CommonDataKinds.Phone.LAST_TIME_CONTACTED,
                ContactsContract.CommonDataKinds.Phone.TIMES_CONTACTED
        };
        // 按照sort_key升序查詢
        asyncQueryHandler.startQuery(0, null, uri, projection, "display_name like ?", new String[]{"%" + name + "%"},
                "sort_key COLLATE LOCALIZED asc");
    }

    private class ContactsAsyncQueryHandler extends AsyncQueryHandler {

        public ContactsAsyncQueryHandler(ContentResolver cr) {
            super(cr);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            list = new ArrayList<>();
            if (cursor != null) {
                contactIdMap = new HashMap<>();
                cursor.moveToFirst();//游标移动到第一页
                for (int i = 0; i < cursor.getCount(); i++ ) {
                    cursor.moveToPosition(i);
                    String name = cursor.getString(1);
                    String number = cursor.getString(2);
                    int contactId = cursor.getInt(3);
                    Long lastTimeContacted = cursor.getLong(4);
                    Long timesContacted = cursor.getLong(5);
                    if (!contactIdMap.containsKey(contactId)) {

//                        // ContentProvider展示数据类似一个单个数据库表
//                        // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
//                        ContentResolver reContentResolverol = getContentResolver();
//                        // 获得DATA表中的电话号码，条件为联系人ID,因为手机号码可能会有多个
//                        Cursor phone = reContentResolverol.query(
//                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
//                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
//                                        + contactId, null, null);
//                        while (phone.moveToNext()) {
//                            String phoneNumber = phone
//                                    .getString(phone
//                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//                            String phoneType = phone
//                                    .getString(phone
//                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
//                            PhoneContact phoneContact = new PhoneContact();
//                            phoneContact.setDesplayName(name);
//                            int a = Integer.parseInt(phoneType);
//                            switch (a) {
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
//                                    phoneContact.setPhoneNum("手机:        "+phoneNumber);
//                                    break;
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
//                                    phoneContact.setPhoneNum("家庭:        "+phoneNumber);
//                                    break;
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
//                                    phoneContact.setPhoneNum("工作:        "+phoneNumber);
//                                    break;
//                                default:
//                                    phoneContact.setPhoneNum("其他:        "+phoneNumber);
//                                    break;
//                            }
//                            phoneContact.setLastTimeContacted(lastTimeContacted);
//                            phoneContact.setTimesContacted(timesContacted);
//                            list.add(phoneContact);
//                        }

                        PhoneContact phoneContact = new PhoneContact();
                        phoneContact.setDesplayName(name);
                        phoneContact.setPhoneNum(number);
                        phoneContact.setLastTimeContacted(lastTimeContacted);
                        phoneContact.setTimesContacted(timesContacted);
                        list.add(phoneContact);
                        contactIdMap.put(contactId, phoneContact);
                    }
                }
                Log.i(this.getClass().toString(), list.size() + "");
            }
            setAdapter(list);

            if(list.size() == 0 && query == "") {
                layoutButton.setVisibility(View.VISIBLE);
            } else {
                layoutButton.setVisibility(View.GONE);
                if (!isUploaded) {
                    isUploaded = true;
                }
            }

            super.onQueryComplete(token, cookie, cursor);
        }
    }
    private void setAdapter(List<PhoneContact> list) {
        adapter = new PhoneContactListAdapter(this, list);
        listView.setAdapter(adapter);
    }
}
